package io.jft.doll.ui.oauth

import android.annotation.SuppressLint
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.g.base.event.ShutDownEvent
import com.g.base.extend.setTimeout
import com.g.base.extend.toast
import com.g.base.help.ProgressDialog
import com.g.base.room.entity.UserEntity
import com.g.base.room.repository.Status
import com.g.base.router.BasePage
import com.g.base.ui.BaseActivity
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import io.jft.doll.R
import io.jft.doll.api.weChatApi
import io.jft.doll.databinding.ActivityOauthBinding
import io.jft.doll.event.WxOauthEvent
import io.jft.doll.model.viewModel.OauthViewModel
import io.jft.doll.router.RouterPage
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by G on 2017/8/15 0015.
 */

@Route(path = BasePage.Oauth)
class OauthActivity : BaseActivity<ActivityOauthBinding>() {
    override var isFullScreen: Boolean = true
    private val oauthViewModel by lazy { ViewModelProviders.of(this).get(OauthViewModel::class.java) }

    @Autowired
    @JvmField
    var oauthFinishNav: String? = null

    private var lastBackPressTime = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        setContentView(R.layout.activity_oauth)
        contentView.data = this
        Glide.with(this).load(R.drawable.img_user_login).crossFade().into(contentView.backgroundImage)
        showContentView()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        ARouter.getInstance().inject(this)
    }

    override fun supportSlideBack(): Boolean = false


    override fun onBackPressed() {
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - lastBackPressTime > 2000L) {
            toast("再按一次 退出程序")
        } else {
            EventBus.getDefault().post(ShutDownEvent())
        }
        lastBackPressTime = currentTimeMillis
    }

    override fun onTokenChange(data: UserEntity?) {
        data ?: return
        //等待dialog关闭
        //有附加参数 跳转到对应页面
        setTimeout(200) {
            if (oauthFinishNav != null) {
                val extras = intent.extras
                extras.remove("oauthFinishNav")
                ARouter.getInstance().build(oauthFinishNav).with(extras).navigation(this)
                finish()
            } else {
                //没有附加参数直接销毁本页面
                finishAfterTransition()
            }
        }
    }

    private val progressDialog by lazy { ProgressDialog() }
    fun onOauthClick(view: View) {
        if (weChatApi.isWXAppInstalled) {
            progressDialog.setStart("正在登录中,可按返回键取消", true)
            val sendReq = weChatApi.sendReq(SendAuth.Req().apply { scope = "snsapi_userinfo" })
            if (!sendReq) {
                progressDialog.setFiled("微信登录失败") { it.dismiss() }
            }
        } else {
            toast("请先安装微信")
        }
    }

    fun onAgreementClick(view: View) {
        ARouter.getInstance().build(RouterPage.OauthAgreementActivity).navigation(this)
    }

    @SuppressLint("CheckResult")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onWxOauthEvent(wxOauthEvent: WxOauthEvent) {
        val data = wxOauthEvent.data

        if (data == null) {
            progressDialog.setFiled("微信登录失败") { it.dismiss(true) }
            return
        }

        if (data.errCode != BaseResp.ErrCode.ERR_OK) {
            progressDialog.setFiled("登录失败") { it.dismiss(true) }
            return
        }
        oauthViewModel.getWxUserInfo(data, this)
                .subscribe(
                        {
                            when (it.status) {
                                Status.Content -> {
                                    toast("微信登录成功")
                                    progressDialog.dismiss()
                                }
                                Status.Error -> {
                                    progressDialog.setFiled(it.error?.message
                                            ?: "微信登录失败") { it.dismiss(true) }
                                }
                            }
                        },
                        {
                            progressDialog.setFiled(it.message ?: "登录失败") { it.dismiss(true) }
                        }
                )
    }
}